package com.my.study.snakeyaml;

import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.introspector.Property;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Representer;

import java.io.InputStream;

/**
 * Yaml处理类
 *
 * @author: yidujun
 * @create: 2021/04/02 09:03
 */
public class YamlParser {

    private static Yaml yaml;

    static {
        Representer representer = new Representer() {
            @Override
            protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) {
                if (null == propertyValue) {
                    return null;
                } else {
                    return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
                }
            }
        };
        yaml = new Yaml(representer);
    }

    /**
     * Java对象序列化为YAML字符串
     *
     * @param object
     * @return
     */
    public static String dumpObject(Object object) {
        return yaml.dump(object);
    }

    /**
     * YAML字符串转换为对象
     *
     * @param content
     * @param type
     * @param <T>
     * @return
     */
    public static <T> T loadObject(String content, Class<T> type) {
        return yaml.loadAs(content, type);
    }

    public static <T> T loadObject(InputStream in, Class<T> type) {
        return yaml.loadAs(in, type);
    }
}
